<script setup lang="tsx">
import { useVbenForm, useVbenModal, type VbenFormProps } from '@vben/common-ui';
import { Page } from '@vben/common-ui';
import { Plus } from '@vben/icons';

import { Button, message, Space, Upload } from 'ant-design-vue';

import { useVbenVxeGrid, type VxeGridProps } from '#/adapter/vxe-table';
import { uploadFile } from '#/api/core/file';
import { addProduct, deleteProduct, getAllProduct } from '#/api/core/product';
import { uuid } from '#/utils';

const enums = {
  platform: [
    {
      label: '快手',
      value: 0,
    },
    {
      label: '抖音',
      value: 1,
    },
  ],
  status: [
    {
      label: '全部',
      value: '',
    },
    {
      label: '待审核',
      value: 0,
      color: '#278DF2',
    },
    {
      label: '通过',
      value: 1,
      color: 'green',
    },
    {
      label: '不通过',
      value: 2,
      color: 'red',
    },
    {
      label: '失效',
      value: -1,
    },
  ],
};
const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,

  schema: [
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'Input',
      // 对应组件的参数
      componentProps: {
        placeholder: '请输入商品名称',
      },
      // 字段名
      fieldName: 'productName',
      // 界面显示的label
      label: '商品名称',
    },
    {
      component: 'RadioGroup',
      componentProps: {
        options: [
          {
            label: '全部',
            value: '',
          },
          ...enums.platform,
        ],
      },
      fieldName: 'shopType',
      label: '平台',
    },
    {
      component: 'Select',
      fieldName: 'checkStatus',
      defaultValue: 0,
      label: '审核状态',
      componentProps: {
        options: enums.status,
        allowClear: true,
      },
    },
  ],
  // 是否可展开
  showCollapseButton: false,
  submitOnChange: true,
  submitOnEnter: false,
  wrapperClass: 'grid-cols-1 md:grid-cols-4',
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: [
    { align: 'left', type: 'checkbox', width: 100 },

    { title: '序号', type: 'seq', width: 50 },
    {
      cellRender: { name: 'CellImage' },
      field: 'img',
      title: '图片',
      width: 120,
    },
    { field: 'title', title: '商品名称' },
    { field: 'productId', sortable: true, title: 'goods_id' },
    {
      cellRender: { name: 'CellTag', options: enums.platform },
      field: 'shopType',
      sortable: true,
      title: '平台',
    },
    { field: 'price', sortable: true, title: '补贴金额' },
    { field: 'createdTime', sortable: true, title: '时间' },
    {
      align: 'right',
      cellRender: {
        attrs: {
          nameField: 'title',
          onClick: onActionClick,
        },
        name: 'CellOperation',
        options: [
          'edit', // 默认的编辑按钮
          'delete', // 默认的删除按钮
        ],
      },
      field: 'operation',
      fixed: 'right',
      headerAlign: 'center',
      showOverflow: false,
      title: '操作',
      width: 100,
    },
  ],
  editConfig: {
    mode: 'row',
    trigger: 'click',
  },
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    response: {
      result: 'list',
      total: 'total',
      list: 'list',
    },
    ajax: {
      query: async ({ page }, formValues) => {
        const res = await getAllProduct({
          currentPage: page.currentPage,
          pageSize: page.pageSize,
          filter: {
            ...formValues,
          },
        });
        return res.data;
      },
    },
  },
  showOverflow: false,
};

const [Grid, gridApi] = useVbenVxeGrid({ formOptions, gridOptions });
function onRefresh() {
  gridApi.query();
}

function onEdit(row: any) {
  console.warn(row);
}
function onDelete(row: any) {
  deleteProduct({ id: row.productId })
    .then(() => {
      message.success({
        content: '删除成功',
        key: 'action_process_msg',
      });
      onRefresh();
    })
    .catch(() => {});
}
function onActionClick({ code, row }: { code: string; row: any }) {
  switch (code) {
    case 'delete': {
      onDelete(row);
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }
    default: {
      break;
    }
  }
}
const [BaseForm, baseFormApi] = useVbenForm({
  // 默认展开
  collapsed: false,
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    colon: true,
    // 所有表单项
    componentProps: {
      class: 'w-[80%]',
    },
  },
  showDefaultActions: false,
  // 垂直布局，label和input在不同行，值为vertical
  // 水平布局，label和input在同一行
  layout: 'horizontal',
  schema: [
    {
      component: 'RadioGroup',
      componentProps: {
        options: enums.platform,
      },
      rules: 'selectRequired',
      fieldName: 'shopType',
      label: '平台',
    },
    {
      component: 'Input',
      fieldName: 'title',
      rules: 'required',
      label: '商品名称',
    },
    {
      component: 'Upload',
      fieldName: 'picture',
      rules: 'required',
      label: '商品缩略图',
    },
    {
      component: 'InputNumber',
      componentProps: {
        min: 0,
      },
      fieldName: 'price',
      rules: 'required',
      suffix: () => '¥',
      label: '原价',
    },
    {
      component: 'InputNumber',
      componentProps: {
        min: 0,
      },
      fieldName: 'discountPrice',
      suffix: () => '¥',
      rules: 'required',
      label: '折扣价格',
    },
    {
      component: 'InputNumber',
      componentProps: {
        min: 0,
      },
      rules: 'required',
      fieldName: 'leaveCount',
      label: '剩余单量',
    },
    {
      component: 'InputNumber',
      componentProps: {
        min: 0,
      },
      rules: 'required',
      fieldName: 'maxCount',
      label: '最大单量',
    },
    {
      component: 'Textarea',
      componentProps: {
        placeholder: '每行一个链接，多个用逗号分隔并换行',
        autoSize: { minRows: 2, maxRows: 5 },
      },
      rules: 'required',
      fieldName: 'proUrls',
      label: '原始链接',
    },
    {
      component: 'Textarea',
      componentProps: {
        autoSize: { minRows: 2, maxRows: 5 },
      },
      fieldName: 'changeProUrl',
      label: '转换链接',
    },
  ],

  wrapperClass: 'grid-cols-1',
});
const [Modal1, modalApi] = useVbenModal({
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    modalApi.setState({
      confirmLoading: true,
    });
    baseFormApi
      .validateAndSubmitForm()
      .then((val) => {
        if (val) {
          const param: any = {
            ...val,
            img: val.picture[0].url,
          };
          delete param.picture;
          addProduct(param).then((res) => {
            if (res.success === true) {
              message.success('添加成功');
              modalApi.close();
              onRefresh();
            } else {
              message.error(res.msg);
            }
          });
        }
      })
      .finally(() => {
        modalApi.setState({
          confirmLoading: false,
        });
      });
  },
});

function addGoods() {
  modalApi.open();
}

const token = computed(() => {
  return localStorage.getItem('token');
});

function beforeUpload(file: any) {
  const formData = new FormData();
  formData.append('file', file);
  uploadFile(formData).then((res) => {
    if (res.success === true) {
      message.success('上传成功');
      baseFormApi.setValues({
        picture: [
          {
            uid: uuid(),
            name: `${res.data.fileName}${res.data.extension}`,
            status: 'done',
            url: res.data.linkUrl,
          },
        ],
      });
    } else {
      message.error(res.msg);
    }
  });
  return false;
}
</script>
<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-tools>
        <Space>
          <Button type="primary" @click="addGoods"> 添加商品 </Button>
          <!-- <Button type="primary" @click="batchUp"> 批量上线 </Button> -->
        </Space>
      </template>
    </Grid>
    <Modal1 class="w-[40vw]" title="批量导入商品">
      <BaseForm>
        <template #picture="slotProps">
          <Upload
            :before-upload="beforeUpload"
            :headers="{
              Authorization: `Bearer ${token}`,
            }"
            :max-count="1"
            accept="image/*"
            action="http://114.55.63.142:8010/api/admin/file/upload-file"
            list-type="picture-card"
            v-bind="slotProps"
            name="file"
          >
            <div>
              <Plus />
              <div style="margin-top: 8px">上传</div>
            </div>
          </Upload>
        </template>
      </BaseForm>
    </Modal1>
  </Page>
</template>

<style lang="scss" scoped>
.page {
  background: white;
  padding: 20px;
}
</style>
<style>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
